package com.boc.langxiang.net;

import com.boc.langxiang.contract.BaseView;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.util.L;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * CreateTime: 2016-03-30上午11:03
 * Author: wjkjinke00@126.com
 * Description:
 */
public abstract class HandleErrorSubscriber<T> extends Subscriber<T> {

    private BaseView mBaseView;

    public HandleErrorSubscriber(BaseView baseView) {
        mBaseView = baseView;
    }


    @Override
    public void onError(Throwable e) {
        mBaseView.hideLoading();
        L.e(e.getMessage());

        if (e instanceof SocketTimeoutException
                || e instanceof ConnectException
                || e instanceof HttpException) {
            mBaseView.onError("", "网络太糟糕了!");
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            mBaseView.onError("", "服务器开小差了!");
        } else if (e instanceof ResultException) {
            ResultException resultException = (ResultException) e;
            L.i(resultException.toString());
            mBaseView.onError(resultException.getCode(),resultException.getMessage());
        } else {
            mBaseView.onError("", "神秘力量导致加载数据失败!");
        }
    }


    @Override
    public void onNext(T response) {
        mBaseView.hideLoading();
        BaseResponse baseResponse = (BaseResponse) response;
        String code = baseResponse.getReturnNo();
        if (code.equals(ResponseCode.SUCCESS)) {
            onSuccess(response);
        }
    }

    public abstract void onSuccess(T response);

    @Override
    public void onCompleted() {

    }
}
